package recomendacaoservidor.controller;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import recomendacaoservidor.classes.Questao;
import recomendacaoservidor.dao.Conexao;
import recomendacaoservidor.dao.QuestaoDAO;
import recomendacaoservidor.classes.Alternativa;
import recomendacaoservidor.classes.Questionario;
import recomendacaoservidor.classes.Servidor;

/**
 * @author Marcelo, Jefferson
 * Processa requição HTTP somente método <code>POST</code>.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public class Controller extends HttpServlet {

    /**
     * Trata as requisições HTTP GET
     * @return HTML
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Redirecionado para a página index.jsp");
        response.sendRedirect("index.jsp");
    }

    /**
     * Trata as requisições HTTP POST, chama e método necessário
     * @return JSON
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;Charset=UTF-8");
        PrintWriter out = response.getWriter();
        String metodo = "";
        XStream json = new XStream(new JettisonMappedXmlDriver());
        json.setMode(XStream.NO_REFERENCES);
        json.alias("questao", Questao.class);
        json.alias("alternativa", Alternativa.class);
        json.alias("servidor", Servidor.class);
        Connection conexao = null;
        try{
            metodo = request.getParameter("metodo");
            conexao = Conexao.getConexao();
            if(metodo != null && metodo.equals("metodoInitQuest")){
                request.getSession().removeAttribute("questoes");
                QuestaoDAO questaoDAO = new QuestaoDAO(conexao);
                Questao questao = questaoDAO.getPrimeiraQuestao();
                out.print(json.toXML(questao));
            }
            else if(metodo != null && metodo.equals("proximaQuestao")){
                Questionario questionario = new Questionario();
                Questao questao = new Questao();
                questao.setQuestao(request.getParameter("questao"));
                questao.setId(Integer.parseInt(request.getParameter("idQuestao")));
                questao.addAlternativa(Integer.parseInt(request.getParameter("idResposta")), request.getParameter("resposta"));
                List<Questao> questoes = null;
                if(request.getSession().getAttribute("questoes") != null)
                    questoes = (ArrayList) request.getSession().getAttribute("questoes");
                else
                    questoes = new ArrayList<Questao>();
                
                questoes.add(questao);
                request.getSession().setAttribute("questoes", questoes);
                Questao novaQuestao = questionario.getProximaQuestao(questoes);
                if(novaQuestao != null)
                    out.print(json.toXML(novaQuestao));
                else{
                    if(questionario.isFinish(questoes.size())){
                        Servidor servidor = questionario.getServidorRecomendado(questoes);
                        out.print(json.toXML(servidor));
                    }
                }
            }
            else if(metodo != null && metodo.equals("?")){}
            else{
                throw new Exception("Método chamado não existe!");
            }
        }
        catch(Exception e){
            json = new XStream(new JettisonMappedXmlDriver());
            json.setMode(XStream.NO_REFERENCES);
            json.toXML(e.getMessage());
        }
        finally{
            try{  if(conexao != null) conexao.close(); } catch (SQLException e) {}
            out.close();
        }
    }
}
